/**
 * 添加商品、添加购物车练习
 * 1. 两个切片：商品切片、购物车切片
 * 2. 商品切片：添加商品
 * 3. 购物车切片： 添加购物车、修改购买数量
 * 
 */
import { createSlice, configureStore } from '@reduxjs/toolkit'
// 1. 商品切片
const goodsSlice = createSlice({
    name: 'goods',
    initialState: {
        goodsList: [] // goods {id:xxx,gname:'小米',price:1999}
    },
    reducers: {
        // 添加购物车
        addGoods(state, { payload }) { // payload {gname:'xx', price:'xx'}
            state.goodsList = [...state.goodsList, {
                id: Math.random().toString(36).slice(2),
                ...payload
            }]
        }
    }
})

const { addGoods } = goodsSlice.actions; // actionCreator获取完毕

// 购物车切片
const carSlice = createSlice({
    name: 'car',
    initialState: {
        carList: []
    },
    reducers: {
        // 添加购物车
        addCar(state, { payload }) { // payload {id,gname,price}
            /**
             * 如果购物车中有该商品，只累加数量，没有该商品，创建
             * 购物车中有没有该商品，如何判断？
             */
            let index = state.carList.findIndex(item => item.id === payload.id)
            if (index === -1) {
                state.carList = [...state.carList, {
                    ...payload,
                    buyNum: 1 // 购买数量
                }]
            } else {
                state.carList[index].buyNum += 1
            }
        }
    }
})

const { addCar } = carSlice.actions

// 创建仓库
const store = configureStore({
    reducer: {
        goods: goodsSlice.reducer,
        car: carSlice.reducer
    }
})

// 监听仓库
store.subscribe(() => {
    console.log(store.getState());
})

// 添加商品
store.dispatch(addGoods({ gname: '小米手机', price: 3999 }))
store.dispatch(addGoods({ gname: '华为手机', price: 9 }))


// 添加购物车
store.dispatch(addCar(store.getState().goods.goodsList[0]))
store.dispatch(addCar(store.getState().goods.goodsList[0]))
store.dispatch(addCar(store.getState().goods.goodsList[1]))